package cn.tedu.tmall.front.mall.dao.repository.impl;

import cn.tedu.tmall.front.mall.dao.repository.IUserCacheRepository;
import cn.tedu.tmall.common.pojo.po.UserStatePO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.Map;

@Slf4j
@Repository
public class UserCacheRepository implements IUserCacheRepository {
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public UserStatePO getUserState(Long id) {
        HashOperations<String, Object, Object> hashOperations = redisTemplate.opsForHash();
        String userStateKey = "user_state_"+id;
        Map<Object, Object> entries = hashOperations.entries(userStateKey);
        log.debug("entries:{}",entries);
        UserStatePO userStatePO = new UserStatePO();
        if (!CollectionUtils.isEmpty(entries)){
            userStatePO.setId(id);
            userStatePO.setAuthorities(String.valueOf(entries.get("authorities")));
            userStatePO.setEnable(Integer.valueOf(String.valueOf(entries.get("enable"))));
        }
        return userStatePO;
    }
}
